package com.xiaowu.friend.service.user.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.xiaowu.common.core.constants.Constants;
import com.xiaowu.common.core.domain.TableDataInfo;
import com.xiaowu.common.core.enums.ExamListType;
import com.xiaowu.common.core.enums.ResultCode;
import com.xiaowu.common.core.utils.ThreadLocalUtil;
import com.xiaowu.common.security.exception.ServiceException;
import com.xiaowu.friend.domain.exam.Exam;
import com.xiaowu.friend.domain.exam.dto.ExamQueryDTO;
import com.xiaowu.friend.domain.exam.vo.ExamVO;
import com.xiaowu.friend.domain.user.UserExam;
import com.xiaowu.friend.manager.ExamCacheManager;
import com.xiaowu.friend.mapper.exam.ExamMapper;
import com.xiaowu.friend.mapper.user.UserExamMapper;
import com.xiaowu.friend.mapper.user.UserMapper;
import com.xiaowu.friend.service.user.IUserExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamServiceImpl implements IUserExamService {

    // 注入UserExamMapper
    @Autowired
    private UserExamMapper userExamMapper;

    // 注入ExamMapper
    @Autowired
    private ExamMapper examMapper;

    // 注入ExamCacheManager
    @Autowired
    private ExamCacheManager examCacheManager;

    // 实现enter方法
    @Override
    public int enter(String token, Long examId) {
        // 根据examId查询Exam
        Exam exam = examMapper.selectById(examId);
        // 如果Exam不存在，抛出异常
        if (exam == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        // 如果竞赛已经结束，抛出异常
        if (exam.getEndTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException(ResultCode.EXAM_IS_FINISH);
        }
        // 获取当前用户ID
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        // 根据用户ID和examId查询UserExam
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getUserId, userId).eq(UserExam::getExamId, examId));
        // 如果用户已报名该竞赛
        if (userExam != null) {
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }

        // 将用户报名信息加入缓存
        examCacheManager.addUserExamCache(userId, examId);
        // 创建新的UserExam
        userExam = new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        // 插入UserExam
        return userExamMapper.insert(userExam);
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(),
                userId);
        List<ExamVO> examVOList;
        if (total == null || total == 0) {
            examVOList = userExamMapper.selectUserExamList(userId);
            examCacheManager.refreshCache(examQueryDTO.getType(), userId);
            total = new PageInfo<>(examVOList).getTotal();
        }else {
            examVOList = examCacheManager.getExamVOList(examQueryDTO, userId);
            total = examCacheManager.getListSize(examQueryDTO.getType(), userId);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList, total);
    }
}
